# -*- coding: utf-8 -*-
import hashlib
import hmac
import json
import time
import uuid
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'dc9a8b39-36a4-458a-9b96-171396abbe7d': {  # dwc 支付宝 定额
        'API_KEY': 'fb3434967ff48565ab066b007c2412b9',
        'gateway': 'http://zohosalesiq.info/api/v3/payment/{}/{}',
        'query_gateway': 'http://zohosalesiq.info/api/v3/orders/{}/{}?time={}&signature={}',
    },
    'c78472cf-3fb1-4828-abd8-01585599274b': {  # dwc 支付宝 定额
        'API_KEY': '943c66e2c215ffb39c2905cfcb899b21',
        'gateway': 'http://zohosalesiq.info/api/v3/payment/{}/{}',
        'query_gateway': 'http://zohosalesiq.info/api/v3/orders/{}/{}?time={}&signature={}',
    },
    'bc6868d8-19d6-4f59-a902-134bf1223003': {  # dwc 支付宝 定额
        'API_KEY': '355635d4ba0a30569a364d3078d2d05a',
        'gateway': 'http://zohosalesiq.info/api/v3/payment/{}/{}',
        'query_gateway': 'http://zohosalesiq.info/api/v3/orders/{}/{}?time={}&signature={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sha256_sign(key, s):
    return hmac.new(key, s.encode('utf8'), hashlib.sha256).hexdigest()


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'payee':
            if k in ['amount', 'settlement']:
                if int(parameter[k] * 100) % 100 != 0:
                    s += k + '=' + str(parameter[k])
                else:
                    s += k + '=' + str(int(parameter[k]))
            else:
                s += k + '=' + str(parameter[k])
        else:
            s += k + '=' + parameter[k]
    _LOGGER.info('mishangpay_v3 sign str : %s', s)
    return _gen_sha256_sign(key, s)


def verify_notify_sign(params, key):
    sign = params.pop('signature')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("mishangpay_v3 sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 商户或客户可接受的支付方式。目前支持的支付方式和取值为
# 银行转账 = 1、支付宝 = 2、微信 = 4。
# 商户仅可指定一种可以接受的支付方式，不可为同一个订单同时指定多种支付方式。
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '4'
    elif service == 'alipay':
        payType = '2'
    else:
        payType = '1'
    return payType


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    request_uuid = uuid.uuid1()
    parameter_dict = OrderedDict((
        ('amount', str(int(pay_amount))),
        ('data', str(pay.id)),
        ('method', _get_pay_type(service)),
        ('return', '{}/pay/api/{}/mishangpay_v3/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('time', str(int(time.time()))),
        ('user', str(pay.user_id)),
    ))
    parameter_dict['request'] = request_uuid
    parameter_dict['signature'] = generate_sign(parameter_dict, api_key)
    parameter_dict.pop('request')
    j = json.dumps(parameter_dict)
    url = _get_gateway(app_id).format(app_id, request_uuid)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    _LOGGER.info("mishangpay_v3 create: url: %s, %s", url, j)
    response = requests.post(url, data=j, headers=headers, timeout=5)
    _LOGGER.info("mishangpay_v3 create: response: %s", response.text)
    j = json.loads(response.text)
    order_db.fill_third_id(pay.id, j['id'])
    return {'charge_info': j['extra']}


# OK
def check_notify_sign(request, app_id):
    data = json.loads(request.body)
    api_key = _get_api_key(app_id)
    _LOGGER.info("mishangpay_v3 notify data: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['data']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('mishangpay_v3 event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['id']
    total_fee = float(data['amount'])
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '4':
        _LOGGER.info('mishangpay_v3 check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.third_id
    app_key = _get_api_key(app_id)
    d = {
        'order': pay_id,
        'time': int(time.time())
    }
    d['signature'] = generate_sign(d, app_key)
    url = _get_query_gateway(app_id).format(app_id, pay_id, d['time'], d['signature'])
    _LOGGER.info(u'mishangpay_v3 query: %s', url)
    response = requests.get(url, verify=False)
    _LOGGER.info(u'mishangpay_v3 query rsp: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = str(data['status'])  # 0 订单未成功 1订单成功
        total_fee = float(data['amount'])
        trade_no = data['id']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '4':
            _LOGGER.info('mishangpay_v3 query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('mishangpay_v3 data error, status_code: %s', response.status_code)
